﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using CCWin;
using SuperMap.Data;

namespace MDF
{
    /// <summary>
    /// 属性映射模块
    /// </summary>
    public partial class SXPPYS : CCSkinMain
    {
        
        private int m_number = 2;
        private int m_lossY = 35;
        private string m_xmlName = "ShuXingPiPei";
        private bool m_check = false;

        private Label m_Label;
        private ComboBox m_ComboBox1;
        private ComboBox m_ComboBox2;

        private Datasources m_Datasources;
        private IO_xml sx_Xml;

        /// <summary>
        /// 初始构造
        /// </summary>
        /// <param name="datasources">传入当前的数据源</param>
        public SXPPYS(Datasources datasources)
        {
            InitializeComponent();

            m_Datasources = datasources;
            sx_Xml = new IO_xml(m_xmlName);
            //数据填充
            Fill_ComboBox();
        }

        /// <summary>
        /// 初始化填充
        /// </summary>
        private void Fill_ComboBox()
        {
            try
            {
                //填充数据集下拉项
                Add_SetOrAttribute(this.Set1_comboBox, true);
                Add_SetOrAttribute(this.Set2_comboBox, true);
                //移除相同项
                this.Set2_comboBox.Items.Remove(this.Set1_comboBox.Text);
                if(this.Set2_comboBox.Items.Count > 0)
                {
                    this.Set2_comboBox.SelectedIndex = 0;
                }
                //填充属性字段下拉项
                Add_SetOrAttribute(this.Set1_Attribute1_Box, false);
                Add_SetOrAttribute(this.Set2_Attribute1_Box, false);
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 检查时用的填充
        /// </summary>
        /// <param name="set1Name"></param>
        /// <param name="set2Name"></param>
        public void Change_ComboBox(string set1Name,string set2Name)
        {
            try
            {
                //先清空
                this.Set1_comboBox.Items.Clear();
                this.Set2_comboBox.Items.Clear();
                //填充名字
                this.Set1_comboBox.Items.Add(set1Name);
                this.Set2_comboBox.Items.Add(set2Name);
                //取消下拉框的控制
                this.Set1_comboBox.SelectionChangeCommitted -= new System.EventHandler(Set_comboBox_SelectionChangeCommitted);
                this.Set2_comboBox.SelectionChangeCommitted -= new System.EventHandler(Set_comboBox_SelectionChangeCommitted);
                //初始选项
                this.Set1_comboBox.SelectedIndex = 0;
                this.Set2_comboBox.SelectedIndex = 0;
                //填充属性字段下下拉框
                Add_SetOrAttribute(this.Set1_Attribute1_Box, false);
                Add_SetOrAttribute(this.Set2_Attribute1_Box, false);
                //确定为检查窗口
                m_check = true;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 添加下拉框选择项
        /// </summary>
        /// <param name="m_ComboBox">需要添加选择项的控件</param>
        /// <param name="m_Choice">该参数为ture时添加Set选择项，为false时添加Attribute选择项</param>
        private void Add_SetOrAttribute(ComboBox m_ComboBox, bool m_Choice)
        {
            try
            {
                //初始清除
                m_ComboBox.Items.Clear();
                //数据填充
                if (m_Choice)
                {
                    //遍历数据源的数据集
                    foreach (Datasource datasource in m_Datasources)
                    {
                        foreach (Dataset dataset in datasource.Datasets)
                        {
                            m_ComboBox.Items.Add(dataset.Name);
                        }
                    }
                    if (m_ComboBox.Items.Count > 0)
                    {
                        m_ComboBox.SelectedIndex = 0;//默认显示第一项
                    }

                }
                //属性填充
                else
                {
                    //获取控件对应数据集名称
                    string setName = Set1_comboBox.Text;
                    if (m_ComboBox.Name.Contains("Set2"))
                    {
                        setName = Set2_comboBox.Text;
                    }
                    //获取当前选择的数据集
                    DatasetVector datasetVector = null;
                    foreach (Datasource datasource in m_Datasources)
                    {
                        if (datasource.Datasets.Contains(setName))
                        {
                            //获得数据后跳出
                            datasetVector = datasource.Datasets[setName] as DatasetVector;
                            break;
                        }
                    }
                    //遍历数据集属性字段
                    foreach (FieldInfo info in datasetVector.FieldInfos)
                    {
                        if (!info.IsSystemField)
                        {
                            //不是系统字段才填充
                            m_ComboBox.Items.Add(info.Name);
                        }
                    }
                    if (m_ComboBox.Items.Count > 0)
                    {
                        m_ComboBox.SelectedIndex = 0;//默认显示第一项
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 添加控件
        /// </summary>
        /// <param name="m_Name"> 属性映射项名称</param>
        private void Add_Controls(string m_Name)
        {
            try
            {
                //判断是否存在
                bool isExist = false;
                foreach (Control control in this.Attribute_Panel.Controls)
                {
                    if (control.Text == m_Name)
                    {
                        isExist = true;
                        break;
                    }
                }
                if (isExist)
                {
                    MessageBox.Show("映射项已存在！", "提示：");
                }
                else
                {
                    //不存在时新建
                    m_Label = new Label
                    {
                        Name = "Attribute" + m_number.ToString() + "_Label",
                        Text = m_Name,
                        Size = this.Attribute1_Label.Size,
                        Location = new Point(this.Attribute1_Label.Location.X, this.Attribute1_Label.Location.Y + (35 * m_number) - m_lossY)
                    };
                    m_ComboBox1 = new ComboBox
                    {
                        Name = "Set1_Attribute" + m_number.ToString() + "_Box",
                        DropDownStyle = ComboBoxStyle.DropDownList,
                        Size = this.Set1_Attribute1_Box.Size,
                        Location = new Point(this.Set1_Attribute1_Box.Location.X, this.Set1_Attribute1_Box.Location.Y + (35 * m_number) - m_lossY)
                    };
                    m_ComboBox2 = new ComboBox
                    {
                        Name = "Set2_Attribute" + m_number.ToString() + "_Box",
                        DropDownStyle = ComboBoxStyle.DropDownList,
                        Size = this.Set2_Attribute1_Box.Size,
                        Location = new Point(this.Set2_Attribute1_Box.Location.X, this.Set2_Attribute1_Box.Location.Y + (35 * m_number) - m_lossY)
                    };
                    //新增控件添加到容器中
                    this.Attribute_Panel.Controls.Add(m_Label);
                    this.Attribute_Panel.Controls.Add(m_ComboBox1);
                    this.Attribute_Panel.Controls.Add(m_ComboBox2);
                    //填充下拉框选项
                    Add_SetOrAttribute(m_ComboBox1, false);
                    Add_SetOrAttribute(m_ComboBox2, false);
                    //计名
                    m_number++;
                } 
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 删除控件
        /// </summary>
        /// <param name="m_Name">属性映射项名称</param>
        private void Delete_Controls(string m_Name)
        {
            try
            {
                //获取属性项对应的空间编号
                string number = "";
                foreach (Control control in this.Attribute_Panel.Controls)
                {
                    if(control.Text == m_Name)
                    {
                        number = control.Name.Substring(9, control.Name.Length - 15);
                        break;
                    }
                }
                if (number == "")
                {
                    MessageBox.Show("映射项不存在或输入有误！");
                }
                else
                {
                    //获取映射项控件名
                    string labelName = "Attribute" + number + "_Label";
                    string comboBox1Name = "Set1_Attribute" + number + "_Box";
                    string comboBox2Name = "Set2_Attribute" + number + "_Box";
                    //删除控件
                    this.Attribute_Panel.Controls.RemoveByKey(labelName);
                    this.Attribute_Panel.Controls.RemoveByKey(comboBox1Name);
                    this.Attribute_Panel.Controls.RemoveByKey(comboBox2Name);
                    //this.Attribute_Panel.Controls.Find(labelName,false);
                    //this.Attribute_Panel.Controls.Find(comboBox1Name, false);
                    //this.Attribute_Panel.Controls.Find(comboBox2Name, false);

                    //调整控件位置
                    for (int i = int.Parse(number) + 1; i < m_number; i++)
                    {
                        //获取其他控件名称
                        labelName = "Attribute" + i.ToString() + "_Label";
                        comboBox1Name = "Set1_Attribute" + i.ToString() + "_Box";
                        comboBox2Name = "Set2_Attribute" + i.ToString() + "_Box";

                        string[] names = new string[] { labelName, comboBox1Name , comboBox2Name };
                        //调整位置
                        foreach (string name in names)
                        {
                            Control control = this.Attribute_Panel.Controls[name];
                            if(control != null)
                            {
                                Point point = new Point(control.Location.X, control.Location.Y - 35);
                                control.Location = point;
                            }
                            else
                            {
                                break;
                            }
                        }                        
                    }
                    //调整减量
                    m_lossY += 35;
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 重置映射项控件
        /// </summary>
        private void Reset_Controls()
        {
            try
            {
                //初始三个不删除
                int count = this.Attribute_Panel.Controls.Count;
                for (int i = 0; i < count; i++)
                {
                    if (i > 2)
                    {
                        this.Attribute_Panel.Controls.Remove(this.Attribute_Panel.Controls[3]);
                    }
                }
                if (this.Attribute_Panel.Controls.Count == 3)
                {
                    m_number = 2;
                    m_lossY = 35;
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 更改数据集选择项时刷新已有字段属性框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Set_comboBox_SelectionChangeCommitted(object sender, EventArgs e)
        {
            try
            {
                //获取控件名（遍历条件）
                string m_Name = "Set1";
                ComboBox m_ComboBox = (ComboBox)sender;
                if (m_ComboBox.Name.Contains("Set1"))
                {
                    //获取选择项
                    string text1 = m_ComboBox.Text;
                    //获取鼠标选择中的项（必须用SelectedItem.ToString()！！！！）
                    //string text2 = m_ComboBox.SelectedItem.ToString();
                    //更新选择项
                    if (!string.IsNullOrEmpty(this.Set2_comboBox.Text))
                    {
                        //判断现选择项是否相同，相同要重置选项
                        if (text1 != this.Set2_comboBox.Text)
                        {
                            //清除后重新填充
                            string text2 = this.Set2_comboBox.Text;
                            this.Set2_comboBox.Items.Clear();
                            Add_SetOrAttribute(this.Set2_comboBox, true);
                            this.Set2_comboBox.Items.Remove(text1);
                            //恢复原选项
                            this.Set2_comboBox.Text = text2;
                        }
                        else
                        {
                            //清除后重新填充
                            this.Set2_comboBox.Items.Clear();
                            Add_SetOrAttribute(this.Set2_comboBox, true);
                            this.Set2_comboBox.Items.Remove(text1);
                            //重置为默认选择项
                            this.Set2_comboBox.SelectedIndex = 0;
                            //遍历容器中的控件，并刷新选择项
                            foreach (Control control in this.Attribute_Panel.Controls)
                            {
                                if (control.Name.Contains("Set2"))
                                {
                                    Add_SetOrAttribute((ComboBox)control, false);
                                }
                            }
                        }
                    }
                }
                else
                {
                    //修改遍历条件
                    m_Name = "Set2";
                }

                //遍历容器中的控件，并刷新选择项
                foreach (Control control in this.Attribute_Panel.Controls)
                {
                    if (control.Name.Contains(m_Name))
                    {
                        Add_SetOrAttribute((ComboBox)control, false);
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 新增映射项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Add_Button_Click(object sender, EventArgs e)
        {
            try
            {
                SXPPYSMZ m_sXYSMZ = new SXPPYSMZ();
                m_sXYSMZ.ShowDialog();
                if (m_sXYSMZ.DialogResult == DialogResult.OK)
                {
                    Add_Controls(m_sXYSMZ.GetName());
                    m_sXYSMZ.Dispose();
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 删除映射项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Delete_Button_Click(object sender, EventArgs e)
        {
            try
            {
                SXPPYSMZ m_sXYSMZ = new SXPPYSMZ();
                m_sXYSMZ.ShowDialog();
                if (m_sXYSMZ.DialogResult == DialogResult.OK)
                {
                    Delete_Controls(m_sXYSMZ.GetName());
                    m_sXYSMZ.Dispose();
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 加载映射文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Open_Button_Click(object sender, EventArgs e)
        {
            try
            {
                if (Set1_comboBox.SelectedIndex != -1 && Set2_comboBox.SelectedIndex != -1)
                {
                    //查询是否存在
                    string infoName = Set1_comboBox.Text + ".." + Set2_comboBox.Text;
                    string infoNameRe = Set2_comboBox.Text + ".." + Set1_comboBox.Text;
                    if (sx_Xml.ReadChildNodesName(infoName).Length > 0 )
                    {
                        //重置控件
                        Reset_Controls();
                        List<string[]> nodesInfo = sx_Xml.ReadChildValues(infoName);
                        //填充初始三项,第一项label忽略
                        this.Set1_Attribute1_Box.Text = nodesInfo[0][1];
                        this.Set1_Attribute1_Box.Text = nodesInfo[0][2];
                        for (int i = 1; i < nodesInfo.Count; i++)
                        {
                            //新增映射项
                            Add_Controls(nodesInfo[i][0]);
                            //填充选择内容
                            m_ComboBox1.Text = nodesInfo[i][1];
                            m_ComboBox2.Text = nodesInfo[i][2];
                        }
                    }
                    else if (sx_Xml.ReadChildNodesName(infoNameRe).Length > 0)
                    {
                        //重置控件
                        Reset_Controls();
                        //交换填充
                        List<string[]> nodesInfo = sx_Xml.ReadChildValues(infoNameRe);
                        //填充初始三项,第一项label忽略
                        this.Set1_Attribute1_Box.Text = nodesInfo[0][2];
                        this.Set1_Attribute1_Box.Text = nodesInfo[0][1];
                        for (int i = 1; i < nodesInfo.Count; i++)
                        {
                            //新增映射项
                            Add_Controls(nodesInfo[i][0]);
                            //填充选择内容
                            m_ComboBox1.Text = nodesInfo[i][2];
                            m_ComboBox2.Text = nodesInfo[i][1];
                        }
                    }
                    else
                    {
                        MessageBox.Show("无当前选择数据集的映射文件~","提示：");
                    }
                }
                else
                {
                    MessageBox.Show("没有选择数据集！", "提示：");
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 保存映射文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Save_Button_Click(object sender, EventArgs e)
        {
            try
            {
                if (Set1_comboBox.SelectedIndex != -1 && Set2_comboBox.SelectedIndex != -1)
                {
                    //判断信息是否存在
                    string dataName = Set1_comboBox.Text + ".." +Set2_comboBox.Text;
                    string dataNameRe = Set2_comboBox.Text + ".." +Set1_comboBox.Text;
                    if (sx_Xml.ReadChildNodesName(dataName).Length > 0 || sx_Xml.ReadChildNodesName(dataNameRe).Length > 0)
                    {
                        if (MessageBox.Show("当前选择数据集的映射文件已存在,是否覆盖已有文件？", "提示:", MessageBoxButtons.OKCancel) == DialogResult.OK)
                        {
                            //删除原有数据
                            sx_Xml.DeleteXml("YingSheInfo",dataName);
                            sx_Xml.DeleteXml("YingSheInfo", dataNameRe);
                            //遍历获取已有控件的信息，并重新填充
                            string childName = "", value1 = "";
                            foreach (Control control in this.Attribute_Panel.Controls)
                            {
                                if (childName == "")
                                {
                                    childName = control.Text;
                                }
                                else if (value1 == "")
                                {
                                    value1 = control.Text;
                                }
                                else
                                {
                                    //获取每行第三个控件时保存一次
                                    string[] m_keys = new string[] { Set1_comboBox.Text, Set2_comboBox.Text };
                                    string[] m_values = new string[] { value1, control.Text };
                                    sx_Xml.WriteXml("YingSheInfo",dataName, childName, m_keys, m_values);
                                    childName = "";
                                    value1 = "";

                                }
                            }
                            MessageBox.Show("保存完成!", "提示：");
                        }
                        
                    }
                    else
                    {
                        //遍历获取已有控件的信息
                        string childName = "", value1 = "";
                        foreach (Control control in this.Attribute_Panel.Controls)
                        {
                            if (childName == "")
                            {
                                childName = control.Text;
                            }
                            else if (value1 == "")
                            {
                                value1 = control.Text;
                            }
                            else
                            {
                                //获取每行第三个控件时保存一次
                                string[] m_keys = new string[] { Set1_comboBox.Text, Set2_comboBox.Text };
                                string[] m_values = new string[] { value1, control.Text };
                                sx_Xml.WriteXml("YingSheInfo", dataName, childName, m_keys, m_values);
                                childName = "";
                                value1 = "";

                            }
                        }
                        MessageBox.Show("保存完成!", "提示：");
                    }
                    if (m_check)
                    {
                        //检查窗口使用完后退出
                        this.DialogResult = DialogResult.OK;
                    }
                }
                else
                {
                    MessageBox.Show("没有选择数据集！", "提示：");
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OK_Button_Click(object sender, EventArgs e)
        {
            try
            {
                if (m_check)
                {
                    //检查窗口退出
                    this.DialogResult = DialogResult.No;
                }
                else
                {
                    //正常退出
                    this.Close();
                }
            }
            catch (Exception )
            {
                throw;
            }
        }
        
    }
}
